package me.ywy.ximalaya;

import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Album {
	String albumId;
	ArrayList<Sound> sounds;
	int pageCount;
	int currentDownCount = 0;
	int currentDownIndex = 0;

	public Album(String albumId) {
		super();
		this.albumId = albumId;
	}

	public void init() {
		//System.out.println(albumHtml);
		sounds = new ArrayList<Sound>();
		currentDownCount = 0;
		currentDownIndex = 0;
		String html = getHtml(Config.ALBUM_HTML_URL + albumId + ".ajax");
		Document doc = Jsoup.parse(html);
		String soundIds = doc.getElementsByClass("personal_body").attr("sound_ids");
		Elements pages = doc.getElementsByClass("pagingBar_page");
		if (pages != null && pages.size() > 0) {
			for (Element el : pages) {
				String page = el.html();
				try {
					pageCount = Integer.valueOf(page);
				} catch (NumberFormatException e) {
				}
			}
			System.out.println("PageCount:" + pageCount);
		}
		String[] ids = soundIds.split(",");
		sounds.clear();
		for (int i = 0; i < ids.length; i++) {
			Sound s = new Sound(ids[i], albumId, i + "");
			if (s.init()) {
				sounds.add(s);
			}
		}
		for (int i = 2; i <= pageCount; i++) {
			loadPage(i);
		}
	}

	public void loadPage(int page) {
		if (page > pageCount) {
			return;
		}
		currentDownCount = 0;
		currentDownIndex = 0;
		String html = getHtml(Config.ALBUM_HTML_URL + albumId + ".ajax?page=" + (page == 1 ? 0 : page));
		Document doc = Jsoup.parse(html);
		String soundIds = doc.getElementsByClass("personal_body").attr("sound_ids");
		String[] ids = soundIds.split(",");
		for (int i = 0; i < ids.length; i++) {
			Sound s = new Sound(ids[i], albumId, (i + (page - 1) * 100) + "");
			if (s.init()) {
				sounds.add(s);
			}
		}
	}

	private String getHtml(String url) {
		String albumHtml = Tools.getHttpData(url);
		int start = albumHtml.indexOf("$(\"#mainbox\").html('") + new String("$(\"#mainbox\").html('").length();
		int end = albumHtml.indexOf("\\n');");
		albumHtml = albumHtml.substring(start, end);
		albumHtml = albumHtml.replace("\\n", "").replace("\\\"", "\"").replace("\\/", "/").replace("\\'", "");
		return albumHtml;
	}

	public void down(final boolean hq) {
		while (true) {
			if (currentDownCount > Config.MAX_DOWN_THREAD) {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				continue;
			}
			if (currentDownIndex == sounds.size()) {
				if (currentDownCount == 0) {
					break;
				}
				continue;
			}
			currentDownCount++;
			new Thread(new Runnable() {
				public void run() {
					Sound sound = sounds.get(currentDownIndex++);
					sound.download(hq);
					currentDownCount--;
				}
			}).start();
		}
	}
}
